package controller.customer;

import com.alibaba.fastjson.JSON;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import pojo.*;
import service.customer.ServiceCustomer;
import service.customer.impl.*;
import util.PageSupport;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 作者：孩子他爹  日期2019/4/10
 * 顾客servlet
 */
@WebServlet(name = "ServletCustomer",urlPatterns = "/ServletCustomer")
public class ServletCustomer extends HttpServlet {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  //控制日期格式
    DecimalFormat    df   = new DecimalFormat("######0.00");    //控制小数输出
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/xml;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter pw=response.getWriter();
        String action=request.getParameter("action");
        ServiceCustomer sc=new ServiceCustomerImpl();   //顾客操作对象
        Customer cto;          //顾客对象
        if("register".equals(action)){
            cto=new Customer();
            String comeFrom=request.getParameter("ComeFrom");
            //接收增加的新闻信息，并调用后台方法，将新闻信息插入数据库
            String uploadFileName = "";
            String fieldName = "";
            //解析请求之前先判断请求类型是否为文件上传类型
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            //指定上传位置
            String headPortraitFilePath = request.getSession().getServletContext().getRealPath("CusImage/");
            File saveDir = new File(headPortraitFilePath);
            //如果目录不存在，就创建目录
            if (!saveDir.exists()) {
                saveDir.mkdir();
            }
            if (isMultipart) {
                //创建文件上传核心类
                FileItemFactory factory = new DiskFileItemFactory(); // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
                ServletFileUpload upload = new ServletFileUpload(factory); // 用以上工厂实例化上传组件
                try {
                    //处理表单请求
                    List<FileItem> items = upload.parseRequest(request);
                    Iterator<FileItem> iter = items.iterator();
                    while (iter.hasNext()) {
                        FileItem item = (FileItem) iter.next();
                        if (item.isFormField()) {// 如果是普通表单控件
                            fieldName = item.getFieldName();// 获得该字段名称
                            if (fieldName.equals("C_name")) {
                                cto.setCusName(item.getString("UTF-8"));    //获得姓名
                            } else if (fieldName.equals("C_loginName")) {
                                cto.setCusLoginName(item.getString("UTF-8"));   //获得登录名
                            } else if (fieldName.equals("C_pwd")) {
                                cto.setCusPassword(item.getString("UTF-8"));    //获得密码
                            } else if (fieldName.equals("C_email")) {
                                cto.setCusEmail(item.getString("UTF-8"));       //获得邮箱
                            } else if (fieldName.equals("C_sex")) {
                                cto.setCusSex(item.getString("UTF-8"));     //获得性别
                            }else if (fieldName.equals("C_hobby")) {
                                cto.setCusHobby((cto.getCusHobby()!=null)?(cto.getCusHobby()+","+
                                        item.getString("UTF-8")):item.getString("UTF-8"));     //获得爱好
                            }else if (fieldName.equals("C_birthday")) {
                                cto.setCusBirthday(sdf.parse(item.getString("UTF-8")));     //获得生日
                            }else if (fieldName.equals("C_code")) {
                                cto.setCusCode(item.getString("UTF-8"));     //获得身份证
                            }
                        } else {// 如果为文件域
                            String fileName = item.getName();// 获得文件名(全路径)
                            if (fileName != null && !fileName.equals("")) {
                                File fullFile = new File(fileName);
                                File saveFile = new File(headPortraitFilePath, fullFile.getName());//将文件保存到指定的路径
                                //System.out.println(saveFile.getPath());
                                item.write(saveFile);
                                uploadFileName = fullFile.getName();
                                cto.setCusPhoto(uploadFileName);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            System.out.println("上传成功之后的文件名：" + cto.getCusPhoto());
            //调用后台的方法，将新闻信息插入数据库中
            int n = sc.addCustomerDao(cto);
            System.out.println(n);
            if(n>0){
                response.sendRedirect("BeforePage/GUIMEI/zhucebingo.html");
            }else if("register".equals(comeFrom)){
                response.sendRedirect("register.jsp?addFlag="+false);
            }else if("cusAdd".equals(comeFrom)){
                response.sendRedirect("BeforePage/Customer/cusAdd.jsp");
            }
        }           //注册操作
        else if("ExistsLoginName".equals(action)){
            String loginName=request.getParameter("loginName");
            //System.out.println(loginName==null || loginName=="");
            if(loginName!="" && loginName!=null && !"".equals(loginName)){
                boolean flag=sc.customerLoginNameExists(loginName)>0;
                pw.write(flag+"");
                pw.flush();
                pw.close();
            }
        }   //注册登录用户名是否已经存在ajax
        else if("login".equals(action)){
            String loginName=request.getParameter("C_loginName");
            String pwd=request.getParameter("C_pwd");
            if(pwd!=null && pwd!="" && !"".equals(pwd) && loginName!=null && loginName!="" && !"".equals(loginName)){
                Customer customer=sc.customerExists(loginName,pwd);
                if(customer!=null){
                    request.getSession().setAttribute("customer",customer);
                    response.sendRedirect("BeforePage\\GUIMEI\\loginbingo.html");
                }else {
                    response.sendRedirect("Cuslogin.jsp?loginExists="+false);
                }
            }
        }   //用户登录操作
        else if("out".equals(action)){
            request.getSession().removeAttribute("loginName");
            String ht=request.getParameter("houtai");
            if(ht==null){
                response.sendRedirect("Cuslogin.jsp");
            }else {
                response.sendRedirect("BeforePage\\Customer\\CusLogin.jsp");
            }

        }   //注销操作
        else if("getBigClass".equals(action)){
            List<BigClass> listBig=sc.getBigClass();
            for (int i = 0; i < listBig.size(); i++) {
                listBig.get(i).setSmallclassList(sc.getSmallclassById(listBig.get(i).getBigId()));
            }
            String bigJson= JSON.toJSONString(listBig);
            pw.write(bigJson);
            pw.flush();
            pw.close();
        }   //得到大小分类
        else if("shoppingCart".equals(action)){
            String strCuId=request.getParameter("cusId");
            String strScStatus=request.getParameter("scStatus");
            if(strCuId!=null && strCuId!="" && !"".equals(strCuId)
                    && strScStatus!=null && strScStatus!="" && !"".equals(strScStatus)){
                long cuId=Long.parseLong(strCuId);
                long scStatuc=Long.parseLong(strScStatus);
                List<ShoppingRecord> listSr=sc.getShoppingRecordByCusId(cuId,scStatuc);
                double totalPrice=0;    //应付包括运费
                double concessionalRate=0;  //优惠价不包括运费
                double yunFei=0;
                for (ShoppingRecord sr:listSr) {
                    concessionalRate+=sr.getDiscountPrice();
                    yunFei+=sr.getGoodsCarriage();
                }
                totalPrice=yunFei+concessionalRate;
                request.setAttribute("totalPrice",totalPrice);
                request.setAttribute("concessionalRate",concessionalRate);
                request.setAttribute("listSr",listSr);
                String url="";
                if(scStatuc==1){
                    url="BeforePage/GUIMEI/gouwuche.jsp";
                }else if(scStatuc==0){
                    url="BeforePage/GUIMEI/gouwuchejilu.jsp";
                }
                //System.out.println(url);
                request.getRequestDispatcher(url).forward(request,response);
            }
        }   //购物车查找
        else if("shopDel".equals(action)){
            String strSuId=request.getParameter("spId");
            if(strSuId!=null && strSuId!="" && !"".equals(strSuId)){
                Long suId=Long.parseLong(strSuId);
                int pd=sc.deleteShoppingRecord(suId);
                pw.write((pd>0)+"");
                pw.flush();
                pw.close();
            }
        }       //删除购物车商品
        else if("updateNumber".equals(action)){
            String sIdstr=request.getParameter("shopId");
            String strNmu=request.getParameter("number");
            if(sIdstr!=null && sIdstr!="" && !"".equals(sIdstr) && !"".equals(strNmu) && strNmu!=null && strNmu!=""){
                Long sId=Long.parseLong(sIdstr);
                pw.write(""+(sc.updateShop(sId,Integer.parseInt(strNmu))>0));
                pw.flush();
                pw.close();
            }
        }   //修改购物车商品数量ajax
        else if("shoppingCartPage".equals(action)){
            String strCuId=request.getParameter("cusId");
            String strScStatus=request.getParameter("statuc");
            String strIndex=request.getParameter("index");
            boolean boCuId=strCuId!=null && strCuId!="" && !"".equals(strCuId);
            boolean boScStatus=strScStatus!=null && strScStatus!="" && !"".equals(strScStatus);
            boolean boIndex=strIndex!=null && strIndex!="" && !"".equals(strIndex);
            if(boCuId&&boScStatus&&boIndex){
                long cuId=Long.parseLong(strCuId);
                long scStatuc=Long.parseLong(strScStatus);
                int index=Integer.parseInt(strIndex);
                index=index<1?1:index;      //判断当前页不能小于1
                PageSupport ps=new PageSupport();
                ps.setTotalCount(sc.getShopCount(cuId,scStatuc));
                ps.setPageSize(5);
                ps.getTotalPages();
                ps.setCurrentPage(index);
                List<ShoppingRecord> listSr=sc.getShoppingRecordByCusId(cuId,scStatuc);
                request.getSession().setAttribute("listSr",listSr); //设置购物车为全局
                double totalPrice=0;    //应付包括运费
                double concessionalRate=0;  //优惠价不包括运费
                double yunFei=0;
                for (ShoppingRecord sr:listSr) {
                    concessionalRate+=(sr.getDiscountPrice()*sr.getScNumber());
                    yunFei+=sr.getGoodsCarriage();
                }
                ps.setList(sc.getShoppingRecordByCusId(cuId,scStatuc,ps));
                totalPrice=yunFei+concessionalRate;
                concessionalRate= Double.parseDouble(df.format(concessionalRate));
                totalPrice= Double.parseDouble(df.format(totalPrice));
                request.setAttribute("totalPrice",totalPrice);
                request.setAttribute("concessionalRate",concessionalRate);
                request.setAttribute("ps",ps);
                request.setAttribute("scStatuc",scStatuc);
                request.setAttribute("gwcurl","shoppingCartPage");
                String url="";
                if(scStatuc==1){
                    url="BeforePage/GUIMEI/gouwuche.jsp";
                }else if(scStatuc==0){
                    url="BeforePage/GUIMEI/gouwuchejilu.jsp";
                }
                //System.out.println(url);
                request.getRequestDispatcher(url).forward(request,response);
            }
        }   //分页显示购物车
        else if("shopSubmission".equals(action)){
            Object obj=request.getSession().getAttribute("listSr");
            String addres=request.getParameter("addres");
            if(obj!=null && obj!="" && addres!=null && addres!=""){
                List<ShoppingRecord> lsr= (List<ShoppingRecord>) obj;
                int ire=sc.addShopRec(lsr,addres);
                if(ire<0){
                    //均未成功
                    request.getRequestDispatcher("BeforePage/GUIMEI/gouwuche.jsp?falg=false").forward(request,response);
                }else {
                    //添加成功
                    showOrd(sc,request,response,"true");
                }
            }
        }   //提交购物车
        else if("ordQuery".equals(action)){
            showOrd(sc,request,response,"");
        }       //查询订单
        else if("addShop".equals(action)){
            String cIdstr=request.getParameter("cusId");
            String gIdstr=request.getParameter("gId");
            String numberStr=request.getParameter("number");
            String statusStr=request.getParameter("statuc");
            if(
                    cIdstr!=null && gIdstr!=null && numberStr!=null && statusStr!=null
                &&  cIdstr!="" && gIdstr!="" && numberStr!="" && statusStr!=""
                            && !"".equals(cIdstr) && !"".equals(gIdstr) && !"".equals(numberStr) && !"".equals(statusStr)
            ){
                Shoppingcar shop=new Shoppingcar();
                shop.setScCusId(Long.parseLong(cIdstr));
                shop.setScGoodsId(Long.parseLong(gIdstr));
                shop.setScNumber(Long.parseLong(numberStr));
                shop.setScStatus(Long.parseLong(statusStr));
                if(sc.addShopGods(shop)>0){
                    pw.write("true");
                }else {
                    pw.write("false");
                }
                pw.flush();
                pw.close();
            }
        }       //添加购物车商品
        else if("froGetName".equals(action)){
            String code=request.getParameter("cusCode");
            String name=request.getParameter("cusName");
            if(code!=null && name!=null && code!="" && name!=null && !"".equals(name) && !"".equals(code)){
                Customer cut=sc.getCusByCodeName(code,name);
                if(cut!=null){
                    request.setAttribute("cutPwd",cut);
                    //验证成功跳到修改密码页面
                    request.getRequestDispatcher("BeforePage/Customer/froGetPwd.jsp").forward(request,response);
                }else {
                    response.sendRedirect("BeforePage/Customer/forGet.jsp?flag=false");
                }
            }
        }      //通过真实姓名身份证验证账号
        else if("froGetPwd".equals(action)){
            String cId=request.getParameter("id");
            String pwd=request.getParameter("cusPassword");
            if(cId!=null && pwd!=null && cId!="" && pwd!=null && !"".equals(pwd) && !"".equals(cId)){
                String falg="false";
                if(sc.updataCuPwd(Long.parseLong(cId),pwd)>0){
                    //验证成功跳到登录页面
                    falg="true";
                }
                request.setAttribute("falgLogin",falg);
                request.getRequestDispatcher("BeforePage/Customer/CusLogin.jsp").forward(request,response);
            }
        }       //修改密码
        else if("updateOrd".equals(action)){
            String strOrdId=request.getParameter("ordId");
            if(strOrdId!=null && !"".equals(strOrdId) && strOrdId!=""){
                int ire=sc.updateOrd(Long.parseLong(strOrdId));
                request.setAttribute("tiJiao",ire>0);
                showOrd(sc,request,response,"");
            }
        }       //接收订单
        else if("loginBackstage".equals(action)){
            String loginName=request.getParameter("C_loginName");
            String pwd=request.getParameter("C_pwd");
            if(pwd!=null && pwd!="" && !"".equals(pwd) && loginName!=null && loginName!="" && !"".equals(loginName)){
                Customer customer=sc.customerExists(loginName,pwd);
                if(customer.getId()!=0){
                    request.getSession().setAttribute("customer",customer);
                    response.sendRedirect("BeforePage\\Customer\\index.jsp");
                }else {
                    response.sendRedirect("BeforePage\\Customer\\CusLogin.jsp?loginExists=false");
                }
            }
        }   //顾客后台登录
        else if("indexShop".equals(action)){
            String strCuId=request.getParameter("cusId");
            String strScStatus=request.getParameter("statuc");
            String strIndex=request.getParameter("index");
            boolean boCuId=strCuId!=null && strCuId!="" && !"".equals(strCuId);
            boolean boScStatus=strScStatus!=null && strScStatus!="" && !"".equals(strScStatus);
            boolean boIndex=strIndex!=null && strIndex!="" && !"".equals(strIndex);
            if(boCuId&&boScStatus&&boIndex){
                long cuId=Long.parseLong(strCuId);
                long scStatuc=Long.parseLong(strScStatus);
                int index=Integer.parseInt(strIndex);
                index=index<1?1:index;      //判断当前页不能小于1
                PageSupport ps=new PageSupport();
                ps.setTotalCount(sc.getShopCount(cuId,scStatuc));
                ps.setPageSize(5);
                ps.getTotalPages();
                ps.setCurrentPage(index);
                List<ShoppingRecord> srs=sc.getShoppingRecordByCusId(cuId,scStatuc,ps);
                ps.setList(srs);
                request.setAttribute("ps",ps);
                request.setAttribute("scStatuc",scStatuc);
                request.setAttribute("gwcurl","indexShop");
                //System.out.println(url);
                request.getRequestDispatcher("BeforePage\\GUIMEI\\guowucheHouTai.jsp").forward(request,response);
            }
        }       //后台顾客操作购物车
    }

    //显示订单
    public void showOrd(ServiceCustomer sc,HttpServletRequest request, HttpServletResponse response,String flag)throws ServletException, IOException{
        Object obj=request.getSession().getAttribute("customer");
        String strIndex=request.getParameter("index");
        String yemian=request.getParameter("yemian");
        if(obj!=null && obj!="" && !"".equals(obj)){
            Long cid=Long.parseLong(((Customer)obj).getId()+"");
            int index=(strIndex==null)?1:Integer.parseInt(strIndex);
            PageSupport ps=new PageSupport();
            ps.setTotalCount(sc.getOrderseCount(cid));
            ps.setPageSize(5);
            ps.getTotalPages();
            ps.setCurrentPage(index);
            ps.setList(sc.getOrderseList(cid,ps.getCurrentPage(),ps.getPageSize()));
            request.setAttribute("ordPs",ps);
            if(yemian==null || yemian=="" || "".equals(yemian)){
                request.setAttribute("servletURL","/ServletCustomer?action=ordQuery");
                request.getRequestDispatcher("BeforePage/GUIMEI/dingdan.jsp?flag="+flag).forward(request,response);
            }else {
                request.setAttribute("servletURL","/ServletCustomer?action=ordQuery&yemian=后台");
                request.getRequestDispatcher("BeforePage/Customer/ordQuery.jsp?flag="+flag).forward(request,response);
            }
        }else {
            request.getRequestDispatcher("../BeforePage/Customer/homepage.jsp").forward(request,response);
        }
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
